/*
 * Widget API. These run in widget scope only. They are not
 * transformed by the runtime to allow safe calls back to the page
 * scope. 
 */
Widget = {
	_messageHandlers: {},
	
	_readyCallback: function() {},
	
	match: function(pattern, callback) {
		__wwBridge.match(pattern, function(matches) {
			if (matches) {
				callback();
			}
		});
	},
	
	matchReport: function(callback) {
		Page.ifIsReport(function(isReport) {
			if (isReport) {
				callback();
			}
		});
	},
	
	bindMessageHandler: function(message, handler) {
		if (!Widget._messageHandlers[message]) {
			Widget._messageHandlers[message] = handler;
		}
	},
	
	getMessageHandler: function(message) {
		return Widget._messageHandlers[message];
	},
	
	unbindMessageHandler: function(message) {
		if (Widget._messageHandlers[message]) {
			delete Widget._messageHandlers[message];
		}
	},
	
	ready: function(callback) {
		Widget._readyCallback = callback;
	},
	
	loadTrustedModule: function(module) {
		LocalEnvironment.trustedModuleQueue[module.name] = module;
		$.pm({
			target: window.parent,
			type: 'tfxTrustedModuleHandshake',
			data: {
				state: 'verify',
				uuid: LocalEnvironment.uuid,
				moduleName: module.name,
				moduleScript: module.script
			}
		});
	},
	
	requestTrustedModulePermission: function(module) {
		var message = 'A widget is requesting permission to load the trusted module "' + module.name + '"';
		message += 'A trusted module has full access to the page it runs on.';
		message += 'This means it has access to your login information, can automate actions you can do manually, and various other things.';
		message += '\n\nDo you wish to allow this module to run?';
		
		if (confirm(message)) {
			if (confirm('Would you like to remember this setting?')) {
				Cloud.savePreference(module.name, 'alwaysRun');
			}
			
			return true;
		}
		else {
			return false;
		}
	}
};

Cloud = {
	hostedFrame: function(options, callback) {
		var frameObj = {
			initialized: false,
			selector: '#' + options.id,
			
			show: function() {
				//__wwBridge.Cloud.showFrame(options.id);
				$w(this.selector).show();
			},
			
			hide: function() {
				//__wwBridge.Cloud.hideFrame(options.id);
				$w(this.selector).hide();
			},
			
			toggle: function() {
				$w(this.selector).toggle();
			}
		};
		
		__wwBridge.Cloud.hostedFrame(options, function() {
			frameObj.initialized = true;	
		});
		
		return frameObj;
	},
	
	getPreference: function(key, callback) {
		var userID = LocalEnvironment.userID;
		var apiKey = LocalEnvironment.apiKey;
		
		$.ajax({
			url: Environment.API_URL + 'users/current/prefs/' + key + '/',
			username: userID,
			password: apiKey,
			dataType: 'json',
			contentType: 'application/json',
			success: function(value) {
				callback(value);
			},
			error: function() {
				alert('error retrieving pref "' + key + '"');
			}
		});
	},
	
	savePreference: function(key, value, callback) {
		var userID = LocalEnvironment.userID;
		var apiKey = LocalEnvironment.apiKey;
		
		$.ajax({
			url: Environment.API_URL + 'users/current/prefs/' + key + '/',
			username: userID,
			password: apiKey,
			dataType: 'json',
			contentType: 'application/json',
			type: 'PUT',
			data: value,
			success: function(value, status, xhr) {
				callback(value);
			},
			error: function() {
				alert('error saving pref "' + key + '"');
			}
		});		
	}
};

UI = {
	_clickEventHandlers: {},
	
	getClickEventHandler: function(hash) {
		return UI._clickEventHandlers[hash];
	},
	
	freeFloatButton: function(options) {
		var waitForInit = function(delegate) {
			if (!this.initialized) {
				setTimeout(delegate, 1);
			}
			else {
				delegate();
			}
		};
	
		var btnObj = {
			initialized: false,
			id: options.id,
			selector: '#' + options.id,
			innerText: options.innerText,
			waitForInit: waitForInit,
			click: function(evtCallback) {
				if (evtCallback) {
					waitForInit(function() {
						$w('#' + options.id, true).click(function() {
							evtCallback();
						});
					});
				}
				else {
					//generate synthetic click event
				}
			}
		};
		
		__wwBridge.UI.freeFloatButton(options, function() {
			btnObj.initialized = true;
		});
		
		return btnObj;
	}
};

Util = {
	_uuids: [],
	
	uuid: function() {
		var uuid = Math.floor(Math.random() * 32768);
		while (Util._uuids[uuid] != undefined) {
			uuid = Math.floor(Math.random() * 32768);
		}
		
		Util._uuids.push(uuid);
		return uuid;
	},
	
	deleteUUID: function(uuid) {
		with ({ uuids : Util._uuids }) {
			if ($.inArray(uuid, uuids) != -1) {
				uuids.splice(uuids.indexOf(uuid), 1);
			}			
		}
	}
}